package com.billing.web.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.billing.model.entity.TUser;
import com.billing.service.UserService;
import com.billing.utils.CaptchaUtil;
import com.billing.utils.MD5Util;

import net.sf.json.JSONObject;

@RequestMapping(value="/login")
@Controller
public class LoginController {

	@Resource
	private UserService userService;
	
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public String login(HttpServletRequest request, Model model){
		return "redirect:../login.jsp";
	}
	@RequestMapping(value="/main")
	public String main(HttpServletRequest request, Model model){
		
		TUser user = (TUser) request.getSession().getAttribute("user");
		if(user!=null){
			return "main";
		}
		return "redirect:../login.jsp";
	}
	@RequestMapping(value="/quit",method=RequestMethod.POST)
	public void quit(HttpServletRequest request, Model model){
		request.getSession().removeAttribute("user");
	}
	
	@RequestMapping(value="/tologin",method=RequestMethod.POST)
	public void toLogin(HttpServletRequest request,HttpServletResponse response){
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		String code=request.getParameter("code").toLowerCase();
		String codeSession=((String) request.getSession().getAttribute("code")).toLowerCase();
		try {
			if (codeSession.equals(code)) {
	            // 验证码通过  
	        	String loginname=request.getParameter("username");
	    		String password=request.getParameter("password");
    			//password=MD5Util.md5Encode(password);
	    		TUser user = userService.getTUser(loginname, password);
	    		if(user!=null){
	    			request.getSession().setAttribute("user",user);
	    			request.getSession().setAttribute("mplist",user.getMplist());
	    			request.getSession().setAttribute("managerid",user.getId());
	    			request.getSession().setAttribute("username",loginname);
	    			request.getSession().setAttribute("password",password);
	    			request.getSession().setAttribute("organizationid", user.getOrganizationId());
	    			response.getWriter().print("{\"code\":\"1\",\"msg\":\"登陆成功\",\"userid\":\""+user.getId()+"\"}");
	    		}else{
	    			response.getWriter().print("{\"code\":\"2\",\"msg\":\"用户名或密码错误\"}");
	    		}
	        }else if(StringUtils.isEmpty(code)) { 
	        	response.getWriter().print("{\"code\":\"2\",\"msg\":\"未填写验证码信息\"}");
	        }else{  
	        	response.getWriter().print("{\"code\":\"2\",\"msg\":\"验证码错误\"}");
	        }
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		
	}
	@RequestMapping("/user/check.jpg")
    public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {  
        // 通知浏览器不要缓存  
        response.setHeader("Expires", "-1");  
        response.setHeader("Cache-Control", "no-cache");  
        response.setHeader("Pragma", "-1");  
        CaptchaUtil util = CaptchaUtil.Instance();  
        // 将验证码输入到session中，用来验证  
        String code = util.getString();  
        request.getSession().setAttribute("code", code);  
        // 输出打web页面  
        ImageIO.write(util.getImage(), "jpg", response.getOutputStream());  
    }  
	//checkCode
	public String checkCode(HttpServletRequest request){
		
		return null;
	}
	
	@RequestMapping(value="/tests")
	public String tests(HttpServletRequest request, Model model){
		request.setAttribute("currentPage",50);
		request.setAttribute("totalPage",60);
		return "test";
	}
	
	/**
	 *App 修改密码
	 * @return
	 */
	@RequestMapping(value="/ModifyPassword" ,method=RequestMethod.POST,produces="text/json;charset=UTF-8")
	@ResponseBody
	public String ModifyPassword(HttpServletRequest request,HttpServletResponse response){
		String oldPassword = null;
		String newPassword = null;
		JSONObject jsonObject = null;
		String msg = null;
		String json = request.getParameter("json");
		try {
			json=java.net.URLDecoder.decode(json,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		jsonObject = JSONObject.fromObject(json);
		try{
			oldPassword =jsonObject.getString("oldPassword");
			newPassword =jsonObject.getString("newPassword");
		}catch(Exception e){
            msg="{\"code\":\"9002\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
            return msg;
		}
		int i = 0;
		try {
			i = userService.updatePassword(newPassword,oldPassword);
		} catch (Exception e) {
			msg = "{\"code\":\"2\",\"msg\":\"修改密码失败\"}";
			return msg;
		}
		if (i <= 0) {
			msg = "{\"code\":\"2\",\"msg\":\"密码输入错误\"}";
			return msg;
		}else{
			msg = "{\"code\":\"1\",\"msg\":\"修改密码成功\"}";
			return msg;
		}
	}
	
}
